package com.fire.market.interceptor;
import com.alibaba.fastjson.JSONObject;
import com.fire.component.cache.local.RedisOperate;
import com.fire.component.dto.Response;
import com.fire.component.extension.BizCommonError;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

public class ApplicationInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userToken = request.getHeader("userToken");
        String userId = request.getHeader("userId");
        String redisToken = RedisOperate.get("user_redis_session:" + userId, String.class);
        if (StringUtils.isEmpty(redisToken)){//用户尚未登陆
            //注意此时如果抛出异常的话无法被捕获
            returnErrorResponse(response, BizCommonError.USER_NOT_LOGIN);
            return false;
        }else if (!userToken.equals(redisToken)){//用户在其它地方登陆
            returnErrorResponse(response, BizCommonError.USER_LOGIN_ANYWHERE);
            return false;
        }
        return true;
    }

    public void returnErrorResponse(HttpServletResponse response, BizCommonError error) throws IOException {
        OutputStream os = null;
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/json");
            os = response.getOutputStream();
            Map<String, Object> responseData = new HashMap<>();
            responseData.put("errCode",error.getErrCode());
            responseData.put("errMsg",error.getErrMsg());
            os.write(JSONObject.toJSONBytes(Response.buildFailure(error.getErrCode(), error.getErrMsg())));
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null){
                os.close();
            }
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        MDC.clear();
    }
}
